<?php

namespace app\admin\controller;

use app\common\model\CommonConfig as ConfigModel;
use think\facade\Db;
use think\Exception;
/**
 * 系统配置
 * @remark 可以在此增改系统的变量和分组,也可以自定义分组和变量,如果需要删除请从数据库中删除
 */
class Config extends Base
{
    /**
     * @var \app\admimn\model\Config
     */
    protected $model = null;

    public function initialize()
    {
        parent::initialize();
        $this->model = new ConfigModel();
    }

    /**
     * @OA\Get(
     *   path="/admin/Config/index",
     *   tags={"配置相关"},
     *   summary="配置首页",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Response(
     *     response=200,
     *     description="Success",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response="500", description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function index()
    {
        $this->refreshFile();
        $siteList = [];
        $groupList = ConfigModel::getGroupList();
        foreach ($groupList as $k => $v) {
            $siteList[$k]['name'] = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list'] = [];
        }
        foreach ($this->model->select() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $value['content'] = json_decode($value['content'], TRUE);
			$value['tip'] = htmlspecialchars($value['tip']);
            $value['disabled'] = true;
            if(!empty($value['rule'])){
                $value['rule'] = json_decode($value['rule'],true);
            }
            //开关处理
            if($value['type'] == 'switch'){
                switch ($value['value']){
                    case 1:
                    case 'true':
                        $value['value'] = true;
                        break;
                    case 0:
                    case 'false':
                        $value['value'] = false;
                        break;
                }
            }
            $siteList[$v['group']]['list'][] = $value;
        }
        $index = 0;
        foreach ($siteList as $k => &$v) {
            $v['active'] = !$index ? true : false;
            $index++;
        }
        $this->success('成功',[
            'siteList'=>$siteList,
            'typeList'=>ConfigModel::getTypeList(),
            'groupList'=>ConfigModel::getGroupList()
        ]);
    }

    /**
     * @OA\Post(
     *     path="/admin/Config/add",
     *     tags={"配置相关"},
     *     summary="配置添加",
     *     @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *     @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property( property="type", type="string", description="前端生成输入框类型" ),
     *                 @OA\Property( property="group", type="string", description="配置组别" ),
     *                 @OA\Property( property="title", type="string", description="前端显示变量中文名称" ),
     *                 @OA\Property( property="name", type="string", description="变量名" ),
     *                 @OA\Property( property="value", type="string", description="变量值" ),
     *                 @OA\Property( property="tip", type="string", description="前端输入框提示文字" ),
     *                 @OA\Property( property="rule", type="string", description="输入框验证规则" ),
     *                 example={"type": "text", "group": "basic","title": "系统名称","name": "siteName","value": "EasyApi","tip": "请输入系统名称","rule": ""}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if(empty($params['title'])){
                    $this->error('中文名称不能为空');
                }
                if(empty($params['name'])){
                    $this->error('英文名称不能为空');
                }
                if(empty($params['rule'])){
                    $params['rule'] = '{}';
                }else{
                    if(empty(json_decode($params['rule'],true))){
                        $this->error('验证规则格式错误，请用json字符串格式');
                    }
                }
                foreach ($params as $k => &$v) {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try {
                    if (in_array($params['type'], ['select', 'selects', 'checkbox', 'radio', 'array'])) {
                        $params['content'] = json_encode(ConfigModel::decode($params['content']), JSON_UNESCAPED_UNICODE);
                    } else {
                        $params['content'] = '';
                    }
                    $result = $this->model->create($params);
                    if ($result !== false) {
                        try {
                            $this->refreshFile();
                        } catch (Exception $e) {
                            $this->error($e->getMessage());
                        }
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error('参数为空');
        }
    }

    /**
     * @OA\Put(
     *     path="/admin/Config/edit",
     *     tags={"配置相关"},
     *     summary="配置编辑",
     *     @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *     @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property( property="name", type="string", description="变量名"  ),
     *                 @OA\Property( property="value", type="string", description="变量值" ),
     *                 example={"name": "siteName","value": "EasyApi"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function edit($ids = NULL)
    {
        $row = $this->request->param();
        $find = $this->model->where(['name'=>$row['name']])->find();
        if (empty($row)) {
            $this->error('参数为空');
        }
        if ($find) {
            if($find['type'] == 'switch'){
                $row['value'] = empty($row['value'])?0:1;
            }
            $result = $this->model->where(['name'=>$row['name']])->save(['value'=>$row['value']]);
            if (!$result) {
                $this->error('操作失败');
            }
            $this->success();
        }else{
            $this->error('无此配置项');
        }

    }

    /**
     * @OA\Delete(path="/admin/Config/delete/{name}",
     *   tags={"配置相关"},
     *   summary="配置删除",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(
     *     name="name",
     *     in="path",
     *     required=true,
     *     description="配置英文名称",
     *     @OA\Schema( type="string" )
     *   ),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function delete($name)
    {
        if(empty($name)){
            $this->error('参数未填');
        }
        $config = ConfigModel::getByName($name);
        if ($config) {
            try {
                $config->delete();
                $this->refreshFile();
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        } else {
            $this->error('无效参数');
        }
    }

    /**
     * @OA\Get(
     *   path="/admin/Config/refreshFile",
     *   tags={"配置相关"},
     *   summary="配置刷新",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Response(
     *     response=200,
     *     description="Success",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response="500", description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function refreshFile()
    {
        $config = [];
        foreach ($this->model->select() as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], TRUE);
            }
            $config[$value['name']] = $value['value'];
        }
        file_put_contents(ROOT_PATH . 'config/systemConfig.php', '<?php' . "\n\nreturn " . var_export($config, true) . ";");
    }

    /**
     * @OA\Post(
     *     path="/admin/Config/addGroup",
     *     tags={"配置相关"},
     *     summary="配置组添加",
     *     @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *     @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property( property="title", type="string", description="配置组中文名" ),
     *                 @OA\Property( property="name", type="string", description="配置组英文名" ),
     *                 example={"title":"基础","name":"basic"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function addGroup(){
        $name = $this->request->post('name');
        $title = $this->request->post('title');
        $description = $this->request->post('description');
        if(empty($name) || empty($title)){
            $this->error('有参数未填');
        }
        $find = Db::name('common_config_group')->where(['name'=>$name])->find();
        if(!empty($find)){
            $this->error('配置组重复');
        }
        $result = Db::name('common_config_group')->insert([
            'name' => $name,
            'title' => $title,
            'description' => $description,
        ]);
        if(!$result){
            $this->error('添加失败');
        }
        $this->success();
    }
    /**
     * @OA\Delete(path="/admin/Config/delGroup/{name}",
     *   tags={"配置相关"},
     *   summary="配置组删除",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(
     *     name="name",
     *     in="path",
     *     required=true,
     *     description="配置组英文名称",
     *     @OA\Schema( type="string" )
     *   ),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function delGroup($name){
        if(empty($name)){
            $this->error('参数未填');
        }
        $find = Db::name('common_config')->where(['group'=>$name])->find();
        if(!empty($find)){
            $this->error('请先删除该配置组的配置项');
        }
        $result = Db::name('common_config_group')->where(['name' => $name ])->delete();
        if(!$result){
            $this->error();
        }
        $this->success();
    }
}
